#!/usr/bin/python
# -*- coding: utf-8 -*-

from elftools.elf.elffile import ELFFile
from elftools.elf.constants import SH_FLAGS

def bm3823_bin_loader(mem_start, bin_buffer):
	bytes_count = len(bin_buffer)
	print("Loading %08d bytes to 0x%08X" % (bytes_count, mem_start))

	return bytes_count

def bm3823_elf_loader(elf_file_dir):
	f = open(elf_file_dir, "rb")
	elffile = ELFFile(f)

	if(not elffile):
		print("File is not ELF!")
		f.close()
		return -1

	header = elffile.header
	entry  = header.e_entry
	sects  = header.e_shnum

	total_size = 0

	for section in elffile.iter_sections():
		sh_flags  = section['sh_flags']
		sh_type   = section['sh_type']
		sh_addr   = section['sh_addr']
		sect_size = section.data_size

#		print("SH_FLAGS: 0x%04X, SH_TYPE:%s, ADDR:0x%08X" % (sh_flags, sh_type, sh_addr))

		if ((sh_flags & (SH_FLAGS.SHF_EXECINSTR | SH_FLAGS.SHF_ALLOC | SH_FLAGS.SHF_WRITE)) and (sh_type != 'SHT_NOBITS')):
			sect_data = section.data()
			bm3823_bin_loader(sh_addr, sect_data)
			total_size += sect_size

	f.close()

	if(total_size == 0):
		return -2

	print("ELF Load DONE, Entry point addr: 0x%08X size = %8d bytes" % (entry, total_size))

	return entry

if __name__ == "__main__":
	bm3823_elf_loader("../demo/uart_test/bin/uart_test.elf")